/**
 * @file 数据库连接和初始化模块
 * @description 使用 Realm 创建和管理数据库连接
 * @author 黄敏
 * @version 1.0.0
 * @since 2025-09-19
 */

import Realm from 'realm'
import { existsSync, mkdirSync } from 'node:fs'
import { join } from 'node:path'
import { app } from 'electron'
import { BrowsingHistoryModel } from './models/browsing-history.model'
import { UserCredentialModel } from './models/user-credential.model'
import { AsyncTaskModel } from './models/async-task.model'
import { BookmarkFolderModel } from './models/bookmark-folder.model'
import { BookmarkItemModel } from './models/bookmark-item.model'

/**
 * Realm 数据库实例
 */
let realm: Realm | null = null

/**
 * 获取数据库文件路径
 * @returns 数据库文件的完整路径
 */
function getDatabasePath(): string {
  const userDataPath = app.getPath('userData')
  const dbDir = join(userDataPath, 'database')

  // 确保数据库目录存在
  if (!existsSync(dbDir)) {
    mkdirSync(dbDir, { recursive: true })
    console.log(`✅ 数据库目录已创建: ${dbDir}`)
  }

  return join(dbDir, 'Fieldano-v2.realm')
}

/**
 * 初始化数据库连接
 * @returns Realm 数据库实例
 */
export function initializeDatabase(): Realm {
  try {
    if (realm) {
      console.log('📊 数据库连接已存在，返回现有实例')
      return realm
    }

    const path = getDatabasePath()

    console.log(`🚀 正在初始化 Realm 数据库: ${path}`)

    // 创建 Realm 数据库连接
    realm = new Realm({
      path,
      deleteRealmIfMigrationNeeded: process.env.NODE_ENV === 'development',
      schema: [
        BrowsingHistoryModel,
        UserCredentialModel,
        BookmarkFolderModel,
        BookmarkItemModel,
        AsyncTaskModel
      ],
      schemaVersion: 5
      // onMigration: (oldRealm: Realm, newRealm: Realm) => {}
    })

    console.log('✅ Realm 数据库初始化成功')
    return realm
  } catch (error) {
    console.error('❌ 数据库初始化失败:', error)
    throw new Error(`数据库初始化失败: ${error}`)
  }
}

/**
 * 获取 Realm 数据库实例
 * @returns Realm 数据库实例
 */
export function getDatabase(): Realm {
  if (!realm) {
    throw new Error('数据库连接未初始化，请先调用 initializeDatabase()')
  }
  return realm
}

/**
 * 关闭数据库连接
 */
export function closeDatabase(): void {
  if (realm) {
    try {
      realm.close()
      realm = null
      console.log('✅ Realm 数据库连接已关闭')
    } catch (error) {
      console.error('❌ 关闭 Realm 数据库连接失败:', error)
    }
  }
}

/**
 * 检查数据库连接状态
 * @returns 是否已连接
 */
export function isDatabaseConnected(): boolean {
  return realm !== null && !realm.isClosed
}

/**
 * 获取数据库统计信息
 * @returns 数据库统计信息
 */
export function getDatabaseStats(): {
  isConnected: boolean
  dbPath: string | null
  schemaVersion: number
  browsingHistoryCount: number
  userCredentialCount: number
  bookmarkFolderCount: number
  bookmarkItemCount: number
  asyncTaskCount: number
} {
  if (!realm) {
    return {
      isConnected: false,
      dbPath: null,
      schemaVersion: 0,
      browsingHistoryCount: 0,
      userCredentialCount: 0,
      bookmarkFolderCount: 0,
      bookmarkItemCount: 0,
      asyncTaskCount: 0
    }
  }

  try {
    const browsingHistoryCount = realm.objects('BrowsingHistory').length
    const userCredentialCount = realm.objects('UserCredential').length
    const bookmarkFolderCount = realm.objects('BookmarkFolder').length
    const bookmarkItemCount = realm.objects('BookmarkItem').length
    const asyncTaskCount = realm.objects('AsyncTask').length

    return {
      isConnected: true,
      dbPath: getDatabasePath(),
      schemaVersion: realm.schemaVersion,
      browsingHistoryCount,
      userCredentialCount,
      bookmarkFolderCount,
      bookmarkItemCount,
      asyncTaskCount
    }
  } catch (error) {
    console.error('❌ 获取数据库统计信息失败:', error)
    return {
      isConnected: false,
      dbPath: null,
      schemaVersion: 0,
      browsingHistoryCount: 0,
      userCredentialCount: 0,
      bookmarkFolderCount: 0,
      bookmarkItemCount: 0,
      asyncTaskCount: 0
    }
  }
}

// ==================== 导出所有相关模块 ====================

// 导出数据库管理器
export {
  checkDatabaseHealth,
  DatabaseManager,
  databaseManager,
  initializeDatabaseManager,
  shutdownDatabaseManager
} from './database-manager'

export { BookmarkManagerService } from './services/bookmark.service'

// 导出服务
export { BrowsingHistoryService } from './services/browsing-history.service'

export { PasswordManagerService } from './services/password-manager.service'

export { AsyncTaskService } from './services/task.service'
// 导出类型定义
export type * from './types'
export { BOOKMARK_MANAGER_CHANNELS } from '~shared/ipc-topic'

// 导出 IPC 通道常量
export { BROWSING_HISTORY_CHANNELS } from '~shared/ipc-topic'
